package org.gangcai.mac.shop.fragment;

import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.classic.common.MultipleStatusView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wuhenzhizao.titlebar.utils.AppUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.gangcai.mac.shop.R;
import org.gangcai.mac.shop.activity.BillDetailActivity;
import org.gangcai.mac.shop.bean.BillBean;
import org.gangcai.mac.shop.bean.GetPartMoneyBean;
import org.gangcai.mac.shop.bean.ReBean;
import org.gangcai.mac.shop.bean.UpdateShopData;
import org.gangcai.mac.shop.constants.Constant;
import org.gangcai.mac.shop.manager.RetrofitManager;
import org.gangcai.mac.shop.oberver.CommonObserver;
import org.gangcai.mac.shop.responsibility.DataResponsibility;
import org.gangcai.mac.shop.rxlife.RxFragment;
import org.gangcai.mac.shop.utils.PromptDialogUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.github.mayubao.pay_library.AliPayReq2;
import io.github.mayubao.pay_library.PayAPI;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import me.leefeng.promptlibrary.PromptDialog;

/**
 * 账单界面
 */
public class BillFragment extends RxFragment implements MultiItemTypeAdapter.OnItemClickListener, OnRefreshListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.billTitle)
    TextView billTitle;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.multiple_status_view)
    MultipleStatusView multipleStatusView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;

    private String mParam1;
    private String mParam2;
    ArrayList<BillBean.InfoBean> dataList = new ArrayList<>();
    private CommonAdapter<BillBean.InfoBean> adapter;
    private PromptDialog prompDialog;


    public BillFragment() {
        // Required empty public constructor
    }

    public static BillFragment newInstance(String param1, String param2) {
        BillFragment fragment = new BillFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_bill, container, false);
        unbinder = ButterKnife.bind(this, view);
        prompDialog = PromptDialogUtils.getPrompDialog(getActivity());
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        int statusBarHeight = AppUtils.getStatusBarHeight(getActivity());
        ((LinearLayout.LayoutParams) billTitle.getLayoutParams()).topMargin = statusBarHeight;
        initView();
        loadData();
    }

    private void loadData() {

        RetrofitManager.create().my_bill(SPUtils.getInstance().getString("uid"))
                .compose(this.<BillBean>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CommonObserver<BillBean>(refreshLayout, multipleStatusView) {
                    @Override
                    public void onSuccess(BillBean value) {
                        if (value.getCode() == Constant.CODE_SUCC) {
                            if (value.getInfo() == null || value.getInfo().size() == 0) {
                                multipleStatusView.showEmpty();
                            } else {
                                dataList.clear();
                                dataList.addAll(value.getInfo());
                                adapter.notifyDataSetChanged();

                            }
                        }
                    }
                });
    }

    private void initView() {
        refreshLayout.setEnableLoadmore(false);
        refreshLayout.setOnRefreshListener(this);
        recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new CommonAdapter<BillBean.InfoBean>(getActivity(), R.layout.fragment_bill_recyclerview_item, dataList) {
            @Override
            protected void convert(ViewHolder holder, final BillBean.InfoBean o, int position) {
                Glide.with(BillFragment.this).load(Constant.IMAGE_PATH + o.getImg()).into((ImageView) holder.getView(R.id.goodImage));
                holder.setText(R.id.goodTitle, o.getGoods_name());
                holder.setText(R.id.goodMoney, o.getMoney());
                //订单编号
                holder.setText(R.id.yiyuqi, o.getStateString());
                //三方回购价
                holder.setText(R.id.time, o.getShould_pay());
                holder.setOnClickListener(R.id.btnRight, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        String type = "2";
                        getPartMoney(type, o);
                    }
                });
            }

        };
        recyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
    }

    private void getPartMoney(final String type, final BillBean.InfoBean o) {
        prompDialog.showLoading("请等待");
        DataResponsibility
                .getInstance()
                .getPartMoney(o.getId(), type, this.<GetPartMoneyBean>bindToLifecycle())
                .flatMap(new Function<GetPartMoneyBean, Observable<ReBean>>() {
                    @Override
                    public Observable<ReBean> apply(GetPartMoneyBean getPartMoneyBean) throws Exception {
                        return DataResponsibility
                                .getInstance()
                                .alipay_repayment(o.getId(), type, BillFragment.this.<ReBean>bindToLifecycle(), getPartMoneyBean.getShould_money());
                    }
                })
                .subscribe(new CommonObserver<ReBean>(prompDialog) {
                    @Override
                    public void onSuccess(ReBean value) {
                        if (value.getCode() != 101) {
                            prompDialog.showError("加载失败,请重试");
                        } else {
                            prompDialog.dismiss();
                            String re = value.getInfo().getStr();

                            aliPay(re);
                        }
                    }
                });
    }

    private void aliPay(String re) {
        //1.创建支付宝支付订单的信息
        String rawAliOrderInfo = re;

        //3.发送支付宝支付请求
        AliPayReq2 aliPayReq = new AliPayReq2.Builder()
                .with(this.getActivity())//Activity实例
                .setRawAliPayOrderInfo(rawAliOrderInfo)//支付宝支付订单信息
                .create()
                .setOnAliPayListener(null);//
        PayAPI.getInstance().sendPayRequest(aliPayReq);

        //关于支付宝支付的回调
        aliPayReq.setOnAliPayListener(new AliPayReq2.OnAliPayListener() {
            @Override
            public void onPaySuccess(String resultInfo) {


            }

            @Override
            public void onPayFailure(String resultInfo) {

            }

            @Override
            public void onPayConfirmimg(String resultInfo) {

            }

            @Override
            public void onPayCheck(String status) {

            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

        BillBean.InfoBean infoBean = dataList.get(position);
        BillDetailActivity.open(infoBean.getOrder_id());
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        loadData();
    }

    @Subscribe
    public void onEvent(UpdateShopData data) {
        loadData();
    }
}
